﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Cofe.Core.Utils
{
    /// <summary>
    /// The default parser store parameters into a 
    /// string something like the following:    
    /// xyz=abc&def=abc de&ghi=jkl
    /// 
    /// to represent & and = uses && and ==.
    /// </summary>
    public class ParamStringSerializer : IPropertySerializer
    {
        #region Constructor

        public ParamStringSerializer(bool alphaOnly)
        {
            _regex = new Regex(
                alphaOnly ? RegexPatterns.ParseAlphaParamStringPattern
                : RegexPatterns.ParseParamStringPattern2);
        }

        #endregion

        #region Methods

        public string PropertyToString(IEnumerable<Tuple<string, string>> properties)
        {
            List<string> propStringList = new List<string>();

            foreach (var tuple in properties)
            {
                var s = string.Format("{0}={1}", tuple.Item1, tuple.Item2)
                    .Replace("&", "");
                propStringList.Add(s);
            }

            return String.Join("&", propStringList.ToArray());
        }

        public IEnumerable<Tuple<string, string>> StringToProperty(string propertyString)
        {
            propertyString = propertyString.Replace("&&", "AmPAmP");
            propertyString = propertyString.Replace("==", "eQuAleQual");
            List<Tuple<string, string>> retVal = new List<Tuple<string, string>>();

            int startPos = 0;

            while (startPos < propertyString.Length)
            {
                var match = _regex.Match(propertyString, startPos);
                if (!match.Success)
                    throw new ArgumentException();
                startPos = match.Index + match.Length;
                string key = match.Groups["key"].Value;
                string value = match.Groups["value"].Value.Replace("AmPAmP", "&").Replace("eQuAleQual", "=");
                retVal.Add(new Tuple<string, string>(key, value));
            }
            return retVal;
        }

        #endregion

        #region Data

        private Regex _regex;

        #endregion

        #region Public Properties

        #endregion

        
    }
}
